package org.skyemoon.hbase.hbasetest.toolkit;

import org.skyemoon.hbase.hbasetest.dto.domain.ImageDTO;

import java.io.*;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件处理工具
 */
public class FileUtil {

    public static List<ImageDTO> listFileAndWriteToSequenceFile(String path) throws IOException {

        List<ImageDTO> result = new ArrayList<>();
        // 获取文件路径列表
        File file = new File(path);
        final File[] files = file.listFiles();

        assert files != null;
        for(File f : files) {
            if(f.isFile()) {
                String fName = f.getName();
                long size = f.length();
                String type = fName.substring(fName.lastIndexOf("."));
                byte[] image = null;
                try {
                    byte[] buffer  =  new byte[(int)size];
                    FileInputStream fileInputStream = new FileInputStream(f);
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    int len;
                    while ((len = fileInputStream.read(buffer)) != -1) {
                        out.write(buffer, 0, len);
                    }
                    image = out.toByteArray();
                    fileInputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                ImageDTO imageReqDTO = ImageDTO.builder()
                        .imageName(fName)
                        .imageSize(size)
                        .imageType(type)
                        .image(image)
                        .build();
                result.add(imageReqDTO);
            }
            if(f.isDirectory()) {
                listFileAndWriteToSequenceFile(f.getPath());
            }
        }
        return result;
    }

    public static long byteArrayToLong(byte[] bytes) {
        ByteBuffer buffer = ByteBuffer.allocate(8);
        buffer.put(bytes, 0, bytes.length);
        buffer.flip();
        return buffer.getLong();
    }

    public static long longFrom8Bytes(byte[] input, int offset, boolean littleEndian){
        long value=0;
        // 循环读取每个字节通过移位运算完成long的8个字节拼装
        for(int  count=0;count<8;++count){
            int shift=(littleEndian?count:(7-count))<<3;
            value |=((long)0xff<< shift) & ((long)input[offset+count] << shift);
        }
        return value;
    }
}
